package com.hospital.wx.controller;

import cn.hutool.core.bean.BeanUtil;
import com.hospital.wx.common.CommonResult;
import com.hospital.wx.controller.form.AddCommentForm;
import com.hospital.wx.controller.form.DeleteCommentForm;
import com.hospital.wx.controller.form.GetCommentsByPostIdForm;
import com.hospital.wx.pojo.Comments;
import com.hospital.wx.service.CommentsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("/patient/user/comment")
@Tag(name = "CommentController", description = "用户评论管理接口")
@Slf4j
public class CommentController {

    @Autowired
    private CommentsService commentsService;

    @PostMapping("/getCommentsByPostId")
    @Operation(summary = "根据文章ID获取评论的基本信息和回复数量")
    @CrossOrigin(origins = "localhost:5173", allowCredentials = "true")
    public CommonResult getCommentsByPostId(@Valid @RequestBody GetCommentsByPostIdForm form) {
        try {
            Map<String, Object> param = BeanUtil.beanToMap(form);
            Map<String, Object> list = commentsService.getCommentsByPostId(param);
            return CommonResult.ok().put(CommonResult.RETURN_RESULT, list);
        } catch (Exception e) {
            log.error("查询过程中出现错误", e);
            return CommonResult.failed("查询过程中出现错误");
        }
    }

    @PostMapping("/add")
    @Operation(summary = "添加/发送评论")
    @CrossOrigin(origins = "localhost:5173", allowCredentials = "true")
    public CommonResult addComment(@Valid @RequestBody AddCommentForm form) {
        try {
            Comments comments = new Comments();
            comments.setPostId(form.getPostId());
            comments.setPatientUserId(form.getUserId());
            comments.setContent(form.getContent());
            int rows = commentsService.addComment(comments);
            if (rows == 1) {
                return CommonResult.ok().put("rows", rows);
            } else {
                return CommonResult.failed("添加失败");
            }

        } catch (Exception e) {
            log.error("添加过程中出现错误", e);
            return CommonResult.failed("添加过程中出现错误");
        }
    }

    @PostMapping("/delete")
    @Operation(summary = "删除评论")
    public CommonResult deleteComment(@Valid @RequestBody DeleteCommentForm form) {
        try {
            Map<String, Object> param = BeanUtil.beanToMap(form);
            int rows = commentsService.deleteComment(param);
            if (rows!=1){
                return CommonResult.failed("删除失败");
            }
            return CommonResult.ok().put("rows", rows);
        } catch (Exception e) {
            log.error("删除评论过程中出现异常", e);
            return CommonResult.failed("删除评论过程中出现异常");
        }
    }
}
